package com.lmt.config.shiro;

import com.lmt.common.util.PasswordUtil;
import com.lmt.config.shiro.filter.authz.AnyPermissionAuthorizationFilter;
import com.lmt.config.shiro.filter.authz.AnyRoleAuthorizationFilter;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Log4j2
@Configuration
public class ShiroConfiguration {

    @Bean
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        log.info("注入ShiroFilter：ShiroConfiguration.shiroFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 登陆Url
        shiroFilterFactoryBean.setLoginUrl("/login");

        // 设置没有权限的Url，如果登陆人访问的Url在下面的拦截器中设置（如：/permission/shiroConfiguration），如果没有权限，则自动
        // 转发到该Url，如果是使用注解的方式配置的权限（如：/permission/userSearch），则会抛出AuthorizationException异常
        // 可以使用全局异常捕捉来转发到该Url（com.lmt.ControllerExceptionAdvice.unauthorizedExceptionHandler）
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        // 添加自定义Filter
        Map<String, Filter> filters = new HashMap<>();
        filters.put("anyRole", new AnyRoleAuthorizationFilter());
        filters.put("anyPermission", new AnyPermissionAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filters);

        // 拦截器.
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 配置不会被拦截的链接 顺序判断
        // 自己的登陆Url
        filterChainDefinitionMap.put("/signIn", "anon");
        // 注册Url不拦截
        filterChainDefinitionMap.put("/userInfo/registered", "anon");
        // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");

        // 需要认证并具有 user:search 权限才能访问
        filterChainDefinitionMap.put("/permission/shiroConfiguration", "authc,perms[user:search]");
        // 需要认证并具有 superAdmin 角色才能访问
        filterChainDefinitionMap.put("/role/shiroConfiguration", "authc,roles[superAdmin]");

        // 拥有admin或者superAdmin中的任何一个角色才能访问
        filterChainDefinitionMap.put("/role/anyRole", "authc,anyRole[\"admin,superAdmin\"]");
        // 拥有 userInfo:add 或者 userInfo:update 中的任何一个角色才能访问
        filterChainDefinitionMap.put("/permission/anyPermission", "authc,anyPermission[\"userInfo:add,userInfo:update\"]");

        // 过滤链定义，从上向下顺序执行，一般将/**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了;
        // authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 设置Session信息的管理
     */
    @Bean
    public SessionManager sessionManager(ShiroRedisSessionDao sessionDao, ShiroRedisCacheManager cacheManager) {
        // 使用自定义的sessionManager，解决Shiro频繁从Redis读取session
        ShiroRedisSessionManager sessionManager = new ShiroRedisSessionManager();
        // SessionManager sessionManager = new DefaultWebSecurityManager();
        sessionManager.setSessionDAO(sessionDao);
        sessionManager.setGlobalSessionTimeout(3000);
        sessionManager.setCacheManager(cacheManager);
        // 是否定时检查session
        sessionManager.setSessionValidationSchedulerEnabled(true);
        return sessionManager;
    }

    /**
     * 设置security信息的管理
     */
    @Bean
    public SecurityManager securityManager(ShiroRealm shiroRealm, CredentialsMatcher credentialsMatcher,
                                           SessionManager sessionManager, ShiroRedisCacheManager cacheManager){
        shiroRealm.setCredentialsMatcher(credentialsMatcher);
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm);
        securityManager.setSessionManager(sessionManager);
        securityManager.setCacheManager(cacheManager);
        return securityManager;
    }

    @Bean
    public CredentialsMatcher credentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName(PasswordUtil.PASSWORD_ALGORITHM_NAME);
        credentialsMatcher.setHashIterations(PasswordUtil.PASSWORD_HASH_ITERATIONS);
        return credentialsMatcher;
    }

    /**
     *  开启shiro aop注解支持.
     *  如果使用代理方式，则需要开启代码支持;
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
